package com.seres.util;

import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.seres.vo.UserExcel;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description : 导出demo
 * @ClassName : ExcelExport
 * @Author : 徐浩
 * @Date: 2020-08-11 15:08
 */
public class ExcelExport {
    public void getExcel(HttpServletResponse response) throws IOException {
        List<UserExcel> list = new ArrayList<>();
        list.add(new UserExcel("张三", 19, "职员"));
        list.add(new UserExcel("李四", 20, "老板"));
        list.add(new UserExcel("王五", 22, "职员"));
        // 通过工具类创建writer，默认创建xls格式
        ExcelWriter writer = ExcelUtil.getWriter();
        //自定义标题别名
        writer.addHeaderAlias("name", "员工姓名");
        writer.addHeaderAlias("job", "岗位");
        writer.addHeaderAlias("age", "年龄");
        // 合并单元格后的标题行，使用默认标题样式
        writer.merge(2, "测试导出Excel");
        // 一次性写出内容，使用默认样式，强制输出标题
        writer.write(list, true);
        // 清空response
        response.reset();
        //out为OutputStream，需要写出到的目标流
        //response为HttpServletResponse对象
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        //设置响应的编码
        response.addHeader("Content-Disposition", "attachment;filename=" + new String(("导出测试文件名").getBytes("gb2312"), "ISO-8859-1") + ".xls");
        response.setCharacterEncoding("utf-8");
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
            writer.flush(out, true);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭writer，释放内存
            writer.close();
        }
        //此处记得关闭输出Servlet流
        IoUtil.close(out);
    }
}
